import {ForceLayout, Graph, GridLayout, ConcentricLayout , Tooltip} from '@antv/g6';
import { useEffect, useRef, useState } from 'react';
export default function Zijinliuxiang({ data }) {
    const chartRef = useRef(null)
    const minSize = 20; // 最小节点尺寸
    const maxSize = 100; // 最大节点尺寸

    //获取当前单位类型
    const IS_CYDW = localStorage.getItem("CURR_IS_CYDW")

    let graph;

    const graphRender = () => {

        console.log(data)
        graph = new Graph({
            container: chartRef.current,
            node: {
                style: {
                    labelText: (d) => d.label,
                    fill: (d) => {
                        let color = ''
                        switch (d.nodeType) {
                            case 'cydw':
                                color = '#FFC454';
                                break;
                            case 'wldw':
                                color = '#4C8EDA';
                                break;
                            case 'zyyw':
                                color = '#ecb5c9';
                                break;
                            default:
                                color = '#569480';
                        }
                        return color
                    },
                    palette: {
                        type: 'group',
                        field: d => d.combo,
                        color: 'tableau',
                    },
                    size: (d) => {
                        let sizeNum;
                        switch (d.nodeType) {
                            case 'cydw':
                                if(IS_CYDW == 1){
                                    sizeNum = 80;
                                }else{
                                    sizeNum = Math.max(minSize, Math.min(maxSize, Math.sqrt(parseInt(d.amount) ) * 30));
                                    sizeNum = 20
                                }
                                break;
                            case 'zyyw':
                                // sizeNum = 20
                                if (d.amount <= 1000) {
                                    sizeNum = 20; // 小值区间
                                } else if (d.amount <= 4000) {
                                    sizeNum = 30; // 中等值区间
                                } else if (d.amount <= 5000) {
                                    sizeNum = 40; // 较大值区间
                                } else {
                                    sizeNum = 50; // 最大值区间
                                }
                                break;

                            case 'wpmc':
                                sizeNum = Math.max(minSize, Math.min(maxSize, Math.sqrt(parseInt(d.amount) ) * 30));
                                break;
                            case 'wldw':
                                if(IS_CYDW == 0){
                                    sizeNum = 80;
                                }else{
                                    if (d.amount <= 50) {
                                        sizeNum = 30; // 小值区间
                                    } else if (d.amount <= 400) {
                                        sizeNum = 40; // 中等值区间
                                    } else if (d.amount <= 2000) {
                                        sizeNum = 50; // 较大值区间
                                    } else {
                                        sizeNum = 60; // 最大值区间
                                    }
                                    break;
                                }
                                break;
                            default:
                                sizeNum = 30;
                        }
                        return sizeNum
                    }
                },
                palette: {
                    type: 'group',
                    field: 'combo',
                },
            },
            edge: {
                style: {
                    labelText: (d) => d.label,
                    lineWidth: 4,
                    stroke: (d) => {
                        let color = ''
                        switch (d.elx) {
                            case 'FK':
                                color = '#F76560';
                                break;
                            case 'SK':
                                color = '#23C343';
                                break;
                            default:
                                color = '#CACACA';
                        }
                        return color
                    },
                    endArrow: true
                },
            },
            combo: {
                type: 'circle', // combo 的形状
                style: {
                    fill: '#E5F7F8', // combo 的填充色
                    stroke: '#2CB8C5', // combo 的边框色
                    lineWidth: 2, // combo 的边框宽度
                    labelText: (d) => d.label
                }
            },
            autoResize: true,
            data: data,
            behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'],
            layout: {
                type: 'combo-combined',
                preventOverlap: true,
                spacing: 20,
                preventComboOverlap: true, // 防止 combo 重叠
                comboPadding: 10, // combo 内部的 padding
                linkDistance: 100,
                nodeSpacing: 20, // 节点之间的最小间距
                collideStrength: 0.8, // 碰撞强度
                outerLayout: new ForceLayout({
                    // nodesep: 30, // 节点间距
                    // ranksep: 60, // 层间距
                    // nodeSize: 30,
                    // minZoom: 1,
                    // maxZoom: 2.5,
                    // rankdir: "LR",
                    // linkDistance: 50,

                    controlPoints: true, // 可选
                    preventOverlap: false,
                }),
                innerLayout: new ConcentricLayout({
                    // collapsed: true,
                    // sortBy: 'id',
                    // nodeSize: 20,
                }),
            },
            animation: false,
            autoFit: 'view',
            fitView: true,
            // fitViewPadding: [100, 100, 100, 100],
            plugins:[{
                type: 'tooltip',
                getContent: (e, items) => {
                    if(items[0].nodeType == undefined || items[0].nodeType == null || items[0].id == 'node8' || items[0].id == 'node11') {
                        return null;
                    }

                    let result = `<h4>${items[0].label}</h4>`;
                    items.forEach((item) => {
                        result += `<p>金额总额: ${item.amount} 万元</p>`;
                    });
                    return result;
                },
            }],
        });

        graph.render();

        graph.on('node:dragend', e => {
            let num = graph.getZoom(); // 获取当前的缩放级别
            graph.zoomTo(num); // 缩放画布至指定比例（绝对缩放）
        });
    }

    useEffect(() => {
        //如果整个图片只有一个节点，则说明图片没有数据，则不渲染界面
        if ( data.nodes.length ==1 ) {
            console.error('Invalid graph data:', data);
            return ( )=>{  };
        }

        if (data) {
            if (graph) graph.destroy(); // 销毁旧实例
                graphRender();
        }

        return () => {
            if (graph && typeof graph.destroy === 'function') {
                graph.destroy();
                graph = null;
            }
        };
    }, [data]);    

    return <div ref={chartRef} style={{ width: '100%', height: '100%' }}></div>
}
